package com.cloudm.technician.ui.modules.personal.change_nick_name

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.cloudm.technician.R
import com.cloudm.technician.extensions.string
import com.cloudm.technician.extensions.toast
import com.cloudm.technician.ui.base.BaseFragment
import kotlinx.android.synthetic.main.fragment_change_nick_name.*

/**
 * 作者: wesley
 * 时间: 2017/12/26
 * 描述: ui
 */
class ChangeNickNameFragment : BaseFragment<ChangeNickNamePresenter>(),
        ChangeNickNameContract.View {

    private var name: String? = null

    override val resource: Int
        get() = R.layout.fragment_change_nick_name

    companion object {
        fun newInstance(name: String?) = ChangeNickNameFragment().apply {
            arguments = Bundle().apply {
                putString("name", name)
            }
        }
    }

    override fun initInject() {
        DaggerChangeNickNameComponent.builder().appComponent(
                appComponent).changeNickNamePresenterModule(
                ChangeNickNamePresenterModule(this)).build().inject(this)
    }

    override fun handleBundle(bundle: Bundle) {
        name = bundle.getString("name")
    }

    override fun initVariables() {

    }

    override fun initViews(view: View) {
        etChangeNickName.setText(name)
    }

    override fun initListener() {

    }

    override fun getNickName(): String? = etChangeNickName.string()

    override fun showNickNameEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_input_nick_name))
    }

    override fun nickNameChangeFailure(errorMsg: String) {
        mContext.toast(errorMsg)
    }

    override fun nickNameChangeSuccess(name: String) {
        mContext.toast(mContext.resources.getString(R.string.nick_name_change_success))
        val intent = Intent().apply {
            putExtras(Bundle().apply {
                putString("name", name)
            })
        }
        val activity = mContext as? ChangeNickNameActivity ?: return
        activity.setResult(Activity.RESULT_OK, intent)
        activity.finish()
    }

    override fun showChangeNickNameDialog() {
        showLoadingDialog(mContext.resources.getString(R.string.nick_name_changing))
    }

    override fun hideChangeNickNameDialog() {
        hideLoadingDialog()
    }

    fun save() {
        presenter?.changeNickName(getNickName())
    }

}